package com.nuc.zyt.day05.nio.demo;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Scanner;

/**
 * @ClassName Client
 * @Description TODO
 * @Author 耀酱
 * @Date 2023/5/31 12:14
 * @Version 1.0
 */

public class Client {
    // 相关属性
    private static final int PORT = 9999;
    private Selector selector;
    private SocketChannel channel;

    public Client(){
        try {
            selector = Selector.open();
            // 连接服务器
            channel = SocketChannel.open(new InetSocketAddress("",PORT));

            channel.configureBlocking(false);

            channel.register(selector, SelectionKey.OP_READ);
            System.out.println("当前客户端准备完成");



        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static void main(String[] args) {
        Client client = new Client();
        // 监听服务端发过来的消息、
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    try {
                        client.readInfo();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();

        Scanner sc = new Scanner(System.in);
        while (sc.hasNext()){
            String s= sc.next();
            try {
                client.sendToServer(s);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


    }

    private void sendToServer(String str) throws IOException {
        channel.write(ByteBuffer.wrap(("耀酱说"+str).getBytes()));
    }

    private void readInfo() throws IOException {
        if(selector.select() > 0){
            Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
            while (iterator.hasNext()){
                SelectionKey selectionKey = iterator.next();
                if(selectionKey.isReadable()){
                    SocketChannel sc = (SocketChannel) selectionKey.channel();
                    ByteBuffer buffer = ByteBuffer.allocate(1024);
                    sc.read(buffer);
                    System.out.println(new String(buffer.array()).trim());

                }
            }
        }
    }
}
